package com.fantasy.servlet;

import com.fantasy.entity.Page;
import com.fantasy.entity.Star;
import com.fantasy.entity.User;
import com.fantasy.entity.Video;
import com.fantasy.service.UserService;
import com.fantasy.service.VideoService;
import com.fantasy.service.impl.UserServiceImpl;
import com.fantasy.service.impl.VideoServiceImpl;
import com.fantasy.utils.CookieUtils;
import com.fantasy.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@WebServlet("/client/user.do")
public class CUserServlet extends BaseServlet{
    //注册service
    private UserService userService = new UserServiceImpl();
    private VideoService videoService = new VideoServiceImpl();

    /**
     *  用户登录
     * @param req 请求
     * @param resp 响应
     */
    public void login(HttpServletRequest req, HttpServletResponse resp){
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        User user = userService.queryByPhoneAndPassword(phone, password);
        resp.setContentType("text/html;charset=utf-8");
        if (user!=null){
            resp.addCookie(new Cookie("userId",user.getId().toString()));
            try {
                resp.sendRedirect("./index.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            resp.addCookie(new Cookie("userId","0"));
            try {
                resp.sendRedirect("./index.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 用户注册
     * @param req 请求
     * @param resp 响应
     */
    public void register(HttpServletRequest req, HttpServletResponse resp){
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        User user = new User();
        user.setPhone(phone);
        user.setPassword(password);
        //更具时间戳给随机用户名
        user.setName(""+new Date().getTime());
        resp.setContentType("text/html;charset = utf-8");
        resp.setHeader("refresh", "3;url='./index.jsp'");
        int count = userService.insert(user);
        if (count>0){
            try {
                PrintWriter writer = resp.getWriter();
                writer.write("注册成功! 3秒后跳转回首页");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                PrintWriter writer = resp.getWriter();
                writer.write("注册失败! 3秒后跳转回首页");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 注销登录状态
     * @param req
     * @param resp
     */
    public void logout(HttpServletRequest req, HttpServletResponse resp){
        resp.addCookie(new Cookie("userId","0"));
        resp.setContentType("text/html;charset=utf-8");
        try {
            PrintWriter writer = resp.getWriter();
            writer.write("注销成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 修改用户信息
     * @param req
     * @param resp
     */
    public void revise(HttpServletRequest req, HttpServletResponse resp){
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String introduction = req.getParameter("introduction");
        Cookie[] cookies = req.getCookies();
        String userId = CookieUtils.getCookie("userId", cookies);
        User user = userService.queryById(Integer.parseInt(userId));
        user.setName(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setPhone(phone);
        user.setIntroduce(introduction);
        int count = userService.update(user);
        resp.setContentType("text/html;charset = utf-8");
        resp.setHeader("refresh", "3;url='./index.jsp'");
        if (count>0){
            try {
                PrintWriter writer = resp.getWriter();
                writer.write("修改成功! 3秒后跳转回首页");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                PrintWriter writer = resp.getWriter();
                writer.write("修改失败! 3秒后跳转回首页");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 更换头像
     * @param req
     * @param resp
     */
    public void reHeadImg(HttpServletRequest req, HttpServletResponse resp){
        String realname = req.getParameter("realname");
        String userId = CookieUtils.getCookie("userId", req.getCookies());
        User user = userService.queryById(Integer.parseInt(userId));
        user.setHeadImg(realname);
        int count = userService.update(user);
        try {
            resp.sendRedirect("./myself.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 滑轮加载视频
     * @param request
     * @param response
     */
    public void pulleyVideo(HttpServletRequest request,HttpServletResponse response){
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), 4);
        int videoType = WebUtils.parseInt(request.getParameter("videoType"), 1);

        Page<Video> pulley = videoService.pulley(pageNo, pageSize, videoType);

        Gson gson=new Gson();
        String video = gson.toJson(pulley);

        response.setContentType("application/json;charset=utf-8");
        try {
            response.getWriter().write(video);
        } catch (IOException e) {
//            e.printStackTrace();
        }
    }

    /**
     *  上床视频
     * @param req
     * @param resp
     */
    public void videoUpdate(HttpServletRequest req,HttpServletResponse resp){
        Cookie[] cookies = req.getCookies();
        int userId = Integer.parseInt(CookieUtils.getCookie("userId", cookies));
        Video video = new Video();
        try {
            video.setName(req.getParameter("name"));
            video.setUserId(userId);
            video.setVideoImg(req.getParameter("imgRealname"));
            video.setUrl( req.getParameter("tvRealname"));
            video.setDescribe(req.getParameter("describe"));
            video.setTypeId(2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int count = videoService.insert(video);
        try {
            resp.sendRedirect("./creation.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  内容管理加载视频
     * @param req
     * @param resp
     */
    public void  manage(HttpServletRequest req,HttpServletResponse resp){
        Cookie[] cookies = req.getCookies();
        String userId = CookieUtils.getCookie("userId", cookies);
        List<Video> videos = videoService.queryByUserId(userId);
        //System.out.println(videos);
        Gson gson=new Gson();
        String video = gson.toJson(videos);

        resp.setContentType("application/json;charset=utf-8");
        try {
            resp.getWriter().write(video);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  删除视频
     * @param req
     * @param resp
     */
    public void videoDelete(HttpServletRequest req,HttpServletResponse resp){
        String videoId = req.getParameter("videoId");
        int delete = videoService.delete(Long.valueOf(videoId));
        System.out.println(delete);
        resp.setContentType("text/html;charset = utf-8");
        try {
            resp.getWriter().write("123");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 点赞视频
     * @param req
     * @param resp
     */
    public void like(HttpServletRequest req,HttpServletResponse resp){
        String videoId = req.getParameter("videoId");
        String userId = req.getParameter("userId");
        resp.setContentType("text/html;charset = utf-8");
        //检测是否已经点赞
        if (videoService.queryByUserIdAndVideoId(Integer.parseInt(userId),Integer.parseInt(videoId))==null){
            //在点赞表中添加数据
            Star star = new Star();
            star.setUserId(Integer.parseInt(userId));
            star.setVideoId(Integer.parseInt(videoId));
            int insert = videoService.insert(star);
            //添加视频表中的点赞数量
            Video video = videoService.queryById(Long.parseLong(videoId));
            video.setStarNum(video.getStarNum()+1);
            int i = videoService.upDate(video);
            try {
                //1 代表成功点赞
                resp.getWriter().write("1");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            //0代表已经点赞过了
            try {
                resp.getWriter().write("0");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    public void toVip(HttpServletRequest req,HttpServletResponse resp){
        String userId = req.getParameter("userId");
        User user = userService.queryById(Integer.parseInt(userId));
        user.setVip(1);
        int count = userService.update(user);
        resp.setContentType("text/html;charset=utf-8");
        try {
            resp.getWriter().write(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
